<?php
class Empeval_LpImport_EmployeeImport_Units {
	
	/**
	 * Tablica obiektów EmpevalUnits gdzie klucz to ExtId (Id działu z bazy LP)
	 * @var EmpevalUnits[]
	 */
	private $_map;
	
	public function __construct() {
		$this->_map = EmpevalUnitsQuery::create()->find()->getArrayCopy('ExtId');
	}
	
	/**
	 * @param Lp LpUnits
	 * @return EmpevalUnits
	 */
	private function _add(LpUnits $lpUnit) {
		$extId = $lpUnit->getId();
		$unit = new EmpevalUnits();
		$unit->setExtId($extId);
		$this->_map[$extId] = $unit;
		return $unit;
	}
	
	/**
	 * @param LpUnits $lpUnit
	 * @return EmpevalUnit
	 */
	private function _getWithAdd(LpUnits $lpUnit) {
		$unit = $this->get($lpUnit->getId());
		if (!($unit instanceof EmpevalUnits))
			$unit = $this->_add($lpUnit);
		return $unit;
	}
	
	/**
	 * @param LpUnits $lpUni
	 */
	private function _updateParentUnit(LpUnits $lpUnit) {
		$parentUnit = $this->_getWithAdd($lpUnit->getUnitsRelatedByParentId());
		$unit = $this->get($lpUnit->getId());
		$unit->setUnitsRelatedByParentId($parentUnit);
	}
	
	/**
	 * @param string $extId
	 * @return EmpevalUnits|NULL
	 */
	public function get($extId) {
		if (key_exists($extId, $this->_map))
			return $this->_map[$extId];
		return null;
	}
	
	/**
	 * @param LpUnits $lpUnit
	 * @return EmpevalUnits
	 */
	public function update(LpUnits $lpUnit) {
		$unit = $this->_getWithAdd($lpUnit);
		$unit->setNamePl($lpUnit->getNamePl());
		$unit->setNameEn($lpUnit->getNameEn());
		if ($lpUnit->getUnitsRelatedByParentId() instanceof LpUnits)
			$this->_updateParentUnit($lpUnit);
		return $unit;
	}
	
}